package com.neuedu.it.newidea.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neuedu.it.newidea.po.User;
import com.neuedu.it.newidea.service.UserService;
import com.neuedu.it.newidea.web.dto.RespEntity;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Map;
import java.util.UUID;

@RestController
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;
    @Value("${my.reg_score}")
    private int score;

     @PostMapping("/reg")
    public RespEntity register(@RequestBody User user) {
         try {
             QueryWrapper<User> qw=new QueryWrapper<>();
             qw.lambda().eq(User::getLoginName, user.getLoginName());
             User haduser= userService.getOne(qw);
             if(haduser != null){return new RespEntity("4000","注册失败，用户名已被注册",null);}
             user.setScore(score);
             userService.save(user);
             return new RespEntity("2000", "注册成功", null);
         } catch (Exception ex) {
             ex.printStackTrace();
             return new RespEntity("5000","注册失败"+ex.getMessage(),null);
         }
     }

    @PostMapping("/login")
    public RespEntity login(String loginName, String loginPwd){
        QueryWrapper<User> qw=new QueryWrapper<>();
        qw.lambda().eq(User::getLoginName, loginName).eq(User::getLoginPwd, loginPwd);
        User user=userService.getOne(qw);
        if(user==null)
            return new RespEntity("4000", "用户名或密码错误", null);
        user.setLoginPwd(null);
        JwtBuilder builder = Jwts.builder();
        builder.setId(UUID.randomUUID().toString());
        builder.setIssuedAt(new java.util.Date());
        builder.setExpiration(new Date(System.currentTimeMillis()+1000*60*60*24));
        builder.signWith(SignatureAlgorithm.HS256,"123456");
        builder.setClaims(
                Map.of("id",user.getId()
                ,"nickName",user.getNickName()
                ,"loginName",user.getLoginName()
                ,"email",user.getEmail()
                ,"score" ,user.getScore()
                ));
        String jwttoken=builder.compact();
        System.out.println( jwttoken);
        return new RespEntity("2000", "登录成功", Map.of("user",user,"token",jwttoken));
    }

}
